package com.xuxu.blog.service.impl;

import com.xuxu.blog.entity.ArticleEntity;
import com.xuxu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.zip.CheckedOutputStream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuxu.common.utils.PageUtils;
import com.xuxu.common.utils.Query;

import com.xuxu.blog.dao.DictDao;
import com.xuxu.blog.entity.DictEntity;
import com.xuxu.blog.service.DictService;


@Service("dictService")
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictDao, DictEntity> implements DictService {
    @Autowired
    private DictDao dictDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<DictEntity> page = this.page(
                new Query<DictEntity>().getPage(params),
                new QueryWrapper<DictEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R findAll() {
        List<DictEntity> dictEntities = dictDao.selectList(null);
        return R.ok("查找成功").put("data",dictEntities);
    }

    /**
     * 传统方式，直接根据条件去查找数据。
     * @param article
     */
    public void DetectExistsAndInsert(ArticleEntity article) {
        QueryWrapper<DictEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("content", article.getCategory());
        DictEntity dict = dictDao.selectOne(wrapper);
        if (dict == null) {
            DictEntity dictEntity = new DictEntity();
            dictEntity.setContent(article.getCategory());
            dictDao.insert(dictEntity);
        }
    }

    /**
     * 通过stream去判断有无值
     * @param article
     */
    public void DetectExistsAndInsert2(ArticleEntity article) {
        List<DictEntity> dictlist = dictDao.selectList(null);
        boolean present = dictlist.stream().filter(d -> d.getContent().equals(article.getCategory())).findAny().isPresent();
        if (!present) {
            DictEntity dictEntity = new DictEntity();
            dictEntity.setContent(article.getCategory());
            dictDao.insert(dictEntity);
        }
    }

}